package org.zzh.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.zzh.domain.system.module.SsModule;
import org.zzh.service.system.module.SsModuleService;

import java.util.List;

@Controller
@RequestMapping("/")
public class LoginController {

    @Autowired
    private SsModuleService ssModuleService;

    @RequestMapping("/main.do")
    public ModelAndView main() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/WEB-INF/pages/home/main");
        return modelAndView;
    }

    @RequestMapping("/toLogin.do")
    public ModelAndView toLogin() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/WEB-INF/pages/home/login");
        return modelAndView;
    }

    @RequestMapping("/login.do")
    public String login(@RequestParam(value = "username", required = false) String username,
                        @RequestParam(value = "password", required = false) String password,
                        ModelAndView modelAndView) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            subject.login(token);
            return "redirect:/main.do";
        } catch (Exception e) {
            System.out.println(e.getMessage());
            modelAndView.addObject("message", "登录失败：" + e.getMessage());
            modelAndView.setViewName("/WEB-INF/pages/home/login");
            return modelAndView.getViewName();
        }
    }

    @RequestMapping("/home.do")
    public String home() {
        List<SsModule> list = ssModuleService.list();
        // 这里可以将模块信息添加到模型中，以便在页面中显示
        return "/WEB-INF/pages/home/home";
    }

    @RequestMapping("/logout.do")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout(); // 登出
        }
        // 重定向到登录页面
        return "redirect:/login.do";
    }

    @RequestMapping("/toUnauthorized")
    public String toUnauthorized() {
        return "/WEB-INF/pages/error/403";
    }
}